<template>
  <div class="container">
    <el-card>
      <!-- 行的布局组件 -->
      <el-row>
        <!-- 列的布局 前面 -->
        <el-col :span="18">
          <el-row>
            <el-form
              ref="clear"
              :inline="true"
              :model="params"
              class="demo-form-inline"
              size="small"
            >
              <el-form-item label="学科名称" prop="subjectName">
                <el-input v-model="params.subjectName"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button plain @click="onClear">清除</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </el-col>
        <!-- 列的布局 后面 -->
        <el-col :span="6" style="text-align: right">
          <el-button type="success" size="small" @click="addSubject">
            <i class="el-icon-edit"></i>
            <span>新增学科</span>
          </el-button>
        </el-col>
      </el-row>
      <!-- 提示文案 -->
      <el-row>
        <el-alert
          :title="`数据一共${total}条`"
          type="info"
          show-icon
          :closable="false"
          class="info"
        >
        </el-alert>
      </el-row>
      <!-- 放置表格 -->
      <el-table
        style="margin-top: 10px"
        :data="lists"
        :header-cell-style="{
          backgroundColor: '#fafafa',
          color: '#909399',
          borderBottom: '3px solid #e8e8e8',
        }"
      >
        <el-table-column label="序号" type="index" />
        <el-table-column label="学科名称" prop="subjectName" />
        <el-table-column label="创建者" prop="username" />
        <!-- 作用域插槽 + 过滤器处理时间格式 -->
        <!-- Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据 -->
        <!-- { "id": 23, "subjectName": "134qwe23r4", "creatorID": 2, "addDate": "2023-03-28T11:51:11.000Z", "isFrontDisplay": 1, "tags": 0, "totals": 0, "twoLevelDirectory": 0, "username": "超级管理员" } -->
        <!--  :formatter="FormatForeGround" -->
        <el-table-column label="创建日期" prop="addDate">
          <template v-slot="{ row }">
            {{ row.addDate | parseTimeByString }}
          </template>
        </el-table-column>
        <!-- formatter 格式化内容 -->
        <el-table-column label="前台是否显示" prop="isFrontDisplay"
          ><template v-slot="{ row }">
            {{ row.isFrontDisplay ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="二级目录" prop="twoLevelDirectory" />
        <el-table-column label="标签" prop="tags" />
        <el-table-column label="题目数量" prop="totals" />
        <el-table-column label="操作" fixed="right" width="280">
          <template  #default="{ row }">
            <el-button type="text" size="small" @click="toSecond(row)"
              >学科分类</el-button
            >
            <el-button type="text" size="small" @click="tolabelPage(row)"
              >学科标签</el-button
            >
            <el-button type="text" size="small" @click="editSubject(row)"
              >修改</el-button
            >
            <el-button type="text" size="small" @click="deleteSubject(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <!-- page-size 每页显示条目个数，支持 .sync 修饰符 -->
      <!-- page-sizes 每页显示个数选择器的选项设置 -->
      <el-pagination
          background
          layout="prev, pager, next,sizes,jumper"
          :current-page="params.page"
          :total="total"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="params.pagesize"
          @current-change="changePage"
          @size-change="changePageSizes"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 新增弹层 -->
    <el-dialog
      :title="`${showText}学科`"
      :visible="showDialog"
      width="30%"
      @close="btnPerCanel"
    >
      <!-- 表单 -->
      <el-form
        label-width="80px"
        ref="SubjectForm"
        :model="formData"
        :rules="rules"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input
            style="width: 100%"
            v-model="formData.subjectName"
            placeholder="请输入学科名称"
          />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="formData.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="frontChange"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button @click="btnPerCanel">取 消</el-button>
          <el-button type="primary" @click="btnPerOK()">确定</el-button>
        </el-row>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 分页组件
// import ForeGround from '@/api/base/baseApi.js'  // 引入前台的枚举
import { subjectsList, remove, add, detail, update } from '@/api/hmmm/subjects.js'
export default {
  data () {
    // 验证输入的学科和表内的学科不一致
    const checkSubjectName = async (rule, value, callback) => {
      // 获取部门学科的名称
      const {
        data: { items }
      } = await subjectsList()
      console.log(items)
      //   判断是否重复 过滤出来请求数据里每一项数据 是否等于
      let isRepeat
      if (this.formData.id) {
        // 编辑
        // 编辑增加排除自己的操作
        isRepeat = items.some(
          (obj) => obj.id !== this.formData.id && obj.subjectName === value
        )
      } else {
        // 新增
        isRepeat = items.some((item) => item.subjectName === value)
      }

      console.log(isRepeat)
      isRepeat
        ? callback(new Error(`学科名称里面存在相同的${value}`))
        : callback()
    }
    return {
      showDialog: false,
      formInline: {
        user: '',
        region: ''
      },
      // 接受数据
      lists: [],
      // 分页
      params: {
        page: 1, // 当前页码
        pages: 2,
        pagesize: 10 // 每页条数
      },
      total: 0, // 总条数
      //   value: true,
      // 单框验证
      formData: {
        subjectName: '',
        // username: '',
        // addDate: '',
        isFrontDisplay: null
        // twoLevelDirectory: '',
        // tags: '',
        // totals: ''
      },
      // 验证规则：必填、提示信息、触发事件
      // 学科的名字不能和其他学科的名字重合
      rules: {
        // 对应函数
        // 验证规则
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          {
            validator: checkSubjectName,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getList()
    // this.getdetail()
  },
  computed: {
    showText () {
      return this.formData.id ? '编辑' : '新增'
    }
  },
  methods: {
    // 清除
    async onClear () {
      console.log(1)
      await this.$refs.clear.resetFields()
      await this.getList(this.params)
    },
    // 搜索
    onSearch () {
      this.getList(this.params)
    },
    // 分页
    changePage (val) {
      console.log(val)
      this.params.page = val
      this.getList()
    },
    changePageSizes (val) {
      this.params.pagesize = val
      this.params.page = 1
      this.getList()
    },
    // 前台是否显示
    // FormatForeGround (row, column, cellValue, index) {
    //   // row 对象 行的数据
    //   // column 列的数据
    //   // cellValue 每一行里面单元格的值
    //   // 遍历枚举里面的数组 找到每一项的id 等于对应的单元格的值
    //   const obj = ForeGround.show.find((item) => item.id === cellValue)
    //   //   如果obj不是空值，则返回obj.value 否则返回一个否
    //   return obj ? obj.value : '未知'
    // },
    // 获取学科列表数据
    async getList () {
      const { data } = await subjectsList(this.params)
      //   console.log(data)
      const { counts, items } = data
      // console.log(items) // lists 数组
      // console.log(pagesize) // 10
      this.lists = items
      this.total = counts
    },
    // 删除学科
    async deleteSubject (id) {
      console.log(id)
      try {
        await this.$confirm('此操作将永久删除该目录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await remove(id)
        //   console.log(id)
        this.getList()
        this.$message.success('删除成功！')
      } catch (err) {
        console.log(err)
      }
    },
    // 新增显示弹窗
    addSubject () {
      this.showDialog = true
    },
    frontChange (val) {
      this.formData.isFrontDisplay = val
    },
    // 点击确认新增成功
    async btnPerOK (id) {
      try {
        // 1.验证表单
        await this.$refs.SubjectForm.validate()
        if (this.formData.id) {
          await update(this.formData)
        } else {
          await add(this.formData)
          this.params.page = 1
        }
        this.getList()
        this.showDialog = false
        this.$message.success(this.formData.id ? '编辑成功' : '新增成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 点击修改提示弹框
    async editSubject (id) {
      // 回填数据->调用详情接口
      const { data } = await detail(id)
      console.log(data)
      this.formData = data
      this.showDialog = true
    },
    // 取消->遮罩层-->关闭弹窗
    btnPerCanel () {
      this.showDialog = false
      //   重置
      this.$refs.SubjectForm.resetFields()
      this.formData = {
        subjectName: '',
        isFrontDisplay: null
      }
    },
    // 点击跳转二级目录
    toSecond (row) {
      // #/subjects/directorys?id=45&name=0987654321234567
      this.$router.push(
        `/subjects/directorys?id=${row.id}&name=${row.subjectName}`
      )
    },
    // 点击跳转到标签页
    tolabelPage (row) {
      // http://hmmm.itheima.net/?#/subjects/tags?id=50&name=123
      this.$router.push(`/subjects/tags?id=${row.id}&name=${row.subjectName}`)
    }
  }
}
</script>

<style scoped lang="less"></style>
